<template>
	<div class="rewardList">
		<el-breadcrumb separator="/">
			<el-breadcrumb-item :to="{ path: '/' }"><i class="lh lh-diaodu fw_100"></i></el-breadcrumb-item>
			<el-breadcrumb-item>活动管理</el-breadcrumb-item>
			<el-breadcrumb-item>平台激励活动</el-breadcrumb-item>
		</el-breadcrumb>
		<div class="content_Box box-shadow mt_15 px_10">
			<h4 class="border-bottom pb_10 mb_20">新增平台激励活动</h4>
			<el-form :model="formData" :rules="rules" ref="formData" label-width="100px" class="mw_800">
				<el-form-item class="form-item" label="活动名称" prop="active_name">
					<el-input v-model="formData.active_name" placeholder="请输入活动名称" class="w_200"></el-input>
				</el-form-item>

				<el-form-item class="form-item" label="活动广告图" prop="cover_image">
					<uploadedit v-model="cover_image" :pic_name="'cover_image'" :pic_url="cover_image" @func="img1"></uploadedit>
					<small>允许上传图片的格式为jpg、jpeg、gif、bmp、png</small>
				</el-form-item>

				<el-form-item class="form-item" label="开始时间" prop="start_date">
					<el-date-picker
						v-model="formData.start_date"
						type="date"
						value-format="yyyy-MM-dd"
						placeholder="选择开始时间"
						:picker-options="{
							disabledDate: time => {
								return time.getTime() > new Date(formData.end_date)
							}
						}"
					>
					</el-date-picker>
				</el-form-item>

				<el-form-item class="form-item" label="结束时间" prop="end_date">
					<el-date-picker
						v-model="formData.end_date"
						type="date"
						value-format="yyyy-MM-dd"
						placeholder="选择结束时间"
						:picker-options="{
							disabledDate: time => {
								return time.getTime() < new Date(formData.start_date)
							}
						}"
					>
					</el-date-picker>
				</el-form-item>
				<el-form-item class="form-item" label="执行城市" prop="city_val">
					<el-select v-model="formData.city_val" placeholder="请选择" @change="changeCity">
						<el-option
							v-for="item in cityList"
							:key="item.id"
							:label="item.city_name"
							:value="`${item.id}|${item.city_name}|${item.city_sn}`"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item class="form-item" label="所属行业" prop="industry_val">
					<el-select v-model="formData.industry_val" placeholder="请选择" @change="changeIndustry">
						<!-- <el-option label="餐饮" value="1"></el-option> -->
						<el-option
							v-for="(item, index) in industryJobList"
							:key="index"
							:label="item.label_name"
							:value="item.id"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item class="form-item" label="岗位名称" prop="job_type_name">
					<el-select v-model="formData.job_type_name" placeholder="请选择" @change="changeJobType">
						<el-option
							v-for="item in job_type"
							:key="item.id"
							:label="item.label_name"
							:value="`${item.id}|${item.label_name}`"
						></el-option>
					</el-select>
				</el-form-item>
				<!-- <el-form-item class="form-item" label="执行商圈" prop="area_val">
					<el-select v-model="area_val" multiple collapse-tags @change="changeBtndialogarea">
						<el-option
							v-for="item in areaList"
							:key="item.id"
							:label="item.area_name"
							:value="`${item.id}|${item.area_name}`"
						></el-option>
					</el-select>
				</el-form-item> -->
				<el-form-item class="form-item" label="人才类型" prop="staff_type">
					<el-select v-model="staff_type" multiple collapse-tags>
						<el-option label="兼职" value="1"></el-option>
						<el-option label="全职" value="2"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item class="w_800" label="统计周期" prop="cycle_val">
					<el-select v-model="formData.cycle_val" style="float: left;">
						<el-option label="每半月" value="month"></el-option>
					</el-select>
					<div style="display: flex; flex-direction: column; float: left; margin: -15px 0 0 15px;">
						<small>每月16日12:00生成上半月（1-15）的平台激励账单；</small>
						<small>每月1日12:00生成上月下半月（16-31）的平台激励账单</small>
					</div>
				</el-form-item>
				<el-form-item class="form-item w_700" label="激励规则" prop="ruleList">
					<div class="rule-item" v-for="(item, index) in formData.ruleList" :key="index">
						<el-form-item :prop="`ruleList.${index}.time_long1`" :rules="rules.time_long1">
							<el-input v-model="item.time_long1" class="fl w_60"></el-input>
						</el-form-item>

						<span class="fl rule-text"> {{ ruleText }} </span>
						<el-form-item :prop="`ruleList.${index}.time_long2`" :rules="rules.time_long2">
							<el-input v-model="item.time_long2" class="fl w_60"></el-input>
						</el-form-item>

						<span class="fl rule-text"> 小时，补贴 </span>
						<el-form-item :prop="`ruleList.${index}.price`" :rules="rules.price">
							<el-input v-model="item.price" class="fl w_60"></el-input>
						</el-form-item>

						<span class="fl rule-text"> 元/小时； </span>
						<div class="pointer text-primary" v-if="index === 0" @click="ruleAdd()">增加</div>
						<div class="pointer text-primary" v-else @click="ruleDelete(index)">删除</div>
					</div>
				</el-form-item>

				<el-form-item>
					<el-button type="primary" @click="submitForm()">保存</el-button>
					<el-button @click="goBack()">返回</el-button>
				</el-form-item>
			</el-form>
		</div>
	</div>
</template>

<script>
const MAX_RULE_COUNT = 5
import { fetchCityList } from '@/api/city.js'
import { fetchLabelList, fetchAreaList } from '@/api/shop.js'
import { createIncentive } from '@/api/activity.js'
import { fetchIndustryJob } from '@/api/label.js'

export default {
	name: 'rewardAdd',
	data() {
		return {
			cover_image: '', // 活动图片
			job_type: '',
			areaList: '',
			area_val: '',
			area_id: [],
			area_name: [],
			cityList: '', // 城市列表
			staff_type: '', // 人才类型
			ruleText: '﹤累计出工时长≤', // 文本变量
			formData: {
				active_name: '', // 活动名称
				start_date: '', // 开始日期时间
				end_date: '', // 结束日期时间
				industry_val: '', // 所属行业
				job_type_name: '', // 岗位名称
				city_val: '', // 城市
				cycle_val: '', // 周期
				ruleList: [
					{
						time_long1: '',
						time_long2: '',
						price: '' // 规则单价
					}
				]
			},
			rules: {
				active_name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
				start_date: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
				end_date: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
				industry_val: [{ required: true, message: '请选择所属行业', trigger: 'change' }],
				job_type_name: [{ required: true, message: '请选择岗位名称', trigger: 'change' }],
				city_val: [{ required: true, message: '请选择执行城市', trigger: 'change' }],
				cycle_val: [{ required: true, message: '请选择周期', trigger: 'change' }],
				ruleList: [{ required: true, message: '请输入规则', trigger: 'blur' }],
				time_long1: [{ required: true, message: '请输入规则', trigger: 'blur' }],
				// time_long2: [{ required: true, message: '请输入规则', trigger: 'blur' }],
				price: [{ required: true, message: '请输入规则', trigger: 'blur' }]
			},
			industryJobList: []
		}
	},
	// computed: {
	// 	end_date() {
	// 		return this.formData.end_date
	// 	}
	// },
	// watch: {
	// 	end_date(val) {
	// 		if (val) {
	// 			this.formData.end_date = this.$moment(val).endOf('month').format('YYYY-MM-DD') + ' 23:59:59'
	// 		}
	// 	}
	// },
	created() {},
	mounted() {
		console.log(this.formData.ruleList)
		// 获取岗位标签
		// this.getLabelList()
		// 获取商圈
		this.getAreaList()
		// 获取城市列表
		this.getCityList()
	},
	methods: {
		date(e) {
			return this.$moment().add('days', e).format('YYYY-MM-DD')
		},
		// 获取岗位
		// async getLabelList() {
		// 	try {
		// 		let ret = await fetchLabelList({
		// 			label_type: 'job_type'
		// 		})
		// 		this.job_type = ret
		// 	} catch (error) {
		// 		console.log('err:', error)
		// 	}
		// },
		//标签接口
		async alljob_type() {
			try {
				let arr = { label_type: 'job_type' }
				// if (this.query.city_id) {
				// 	arr = { city_id: this.query.city_id, ...arr }
				// }
				let ret = await fetchIndustryJob(arr)
				this.mesarr = ret
				// this.dataMes.mesarr = ret
			} catch (err) {
				console.log('获取岗位报错', err)
			}
		},
		changeJobType() {
			console.log(this.formData.job_type_name)
			let [id, name] = this.formData.job_type_name.split('|')
			this.label_id = id
			this.label_name = name
		},

		// 获取商圈
		async getAreaList() {
			try {
				let ret = await fetchAreaList()
				ret.list.forEach(item => {
					item.value = item.area_name
				})
				this.areaList = ret.list
			} catch (err) {
				console.log('err:', err)
			}
		},
		changeBtndialogarea() {
			let area_id = []
			this.area_val.forEach(item => {
				console.log(item)
				let [id, name] = item.split('|')
				console.log(id)
				area_id.push(id)
			})

			this.area_id = JSON.stringify(area_id)
			console.log(this.area_id)
		},

		// 获取城市列表
		async getCityList() {
			try {
				let ret = await fetchCityList()
				console.log(ret)
				this.cityList = ret.list
			} catch (err) {
				console.log('err:', err)
			}
		},

		// 监听城市val变化
		changeCity() {
			console.log(this.formData.city_val)
			let [id, name, city_sn] = this.formData.city_val.split('|') // es6 数组解构赋值
			this.city_id = id
			this.city_name = name
			this.city_sn = city_sn
			this.getIndustryJob()
			this.changeIndustry()
			this.formData.industry_val = ''
		},

		async getIndustryJob() {
			try {
				let ret = await fetchIndustryJob({
					city_id: this.city_id
				})

				this.industryJobList = ret
			} catch (err) {
				console.log(err)
			}
		},

		changeIndustry() {
			this.formData.job_type_name = ''
			this.label_id = ''
			this.label_name = ''
			this.job_type = this.industryJobList.filter(x => x.id == this.formData.industry_val)[0].children
		},

		img1(data) {
			this.cover_image = data
		},

		// 新增规则
		ruleAdd() {
			if (this.formData.ruleList.length >= MAX_RULE_COUNT) {
				return this.$message({
					message: `最多添加${MAX_RULE_COUNT}条规则`,
					type: 'warning'
				})
			}
			this.formData.ruleList.push({
				time_long1: '',
				time_long2: '',
				price: '' // 规则单价
			})
		},

		// 删除规则
		ruleDelete(index) {
			this.formData.ruleList.splice(index, 1)
		},

		// 确认添加
		async submitForm() {
			let validate = await this.$refs.formData.validate().catch(err => err)
			if (!validate) {
				this.$message.error('请输入必填项')
				return
			}
			// 验证成功  提交后台
			this.addActivity()
		},

		// 创建添加活动
		async addActivity() {
			try {
				let ruleData = []
				let rule = this.formData.ruleList
				rule.forEach(item => {
					console.log(item)
					ruleData.push({
						days: {
							start: item.time_long1,
							end: item.time_long2
						},
						reward_type: 'money',
						reward: item.price
					})
				})
				let data = {
					name: this.formData.active_name,
					ad_picture: this.cover_image,
					time_start: this.formData.start_date + ' 00:00:00',
					time_end: this.formData.end_date + ' 23:59:59',
					industry: this.formData.industry_val,
					job_type: this.label_id,
					city_id: this.city_id,
					area_id: this.area_id, // 2020-03-11 暂不添加执行商圈 默认传空数组
					area_name: this.area_name,
					work_type: this.staff_type,
					cycle: this.formData.cycle_val,
					rule: ruleData
				}
				await createIncentive(data)
				this.$message.success('添加成功')
				setTimeout(() => {
					this.$router.go(-1)
				}, 1500)
			} catch (err) {
				console.log('error:', err)
			}
		},

		// 返回
		goBack() {
			this.$router.go(-1)
		}
	}
}
</script>

<style>
.form-item {
	padding: 10px 0;
}
.rule-item {
	display: flex;
	margin-bottom: 20px;
}
.rule-item span {
	color: #888;
}
.rule-text {
	margin: 0 20px;
}
.add-btn {
	color: #fff !important;
}
</style>



// WEBPACK FOOTER //
// src/components/reward/Add.vue